package pt.mauromad.guias.service;

import static pt.mauromad.guias.utils.CastUtils.cast;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import pt.mauromad.guias.dao.DomainDao;
import pt.mauromad.guias.dao.UserDao;

@Service
public class UserService extends DaoService<UserDao, Long> {
	public UserService() {
		super(UserDao.class);
	}

	public UserDao get(String fullUsername) {
		String[] pair = fullUsername.split("\\\\");
		Criteria c = sessionFactory.getObject().getCurrentSession().createCriteria(UserDao.class, "user");
		c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		c.createAlias("user.domain", "domain");
		c.add(Restrictions.eq("domain.domain", pair[0]));
		c.add(Restrictions.eq("user.username", pair[1]));
		List<UserDao> users = cast(c.list());
		return users.size() > 0 ? users.get(0) : null;
	}

	public UserDao get(DomainDao domain, String username) {
		UserDao user = one("where domain_id = :0 and username = :1", domain.getId(), username);
		if (user == null)
			throw new IllegalArgumentException("no such user in domain:" + username);
		return user;
	}

	public Long getId(DomainDao domain, String username) {
		Criteria c = sessionFactory.getObject().getCurrentSession().createCriteria(UserDao.class);
		c.add(Restrictions.eq("username", username));
		c.add(Restrictions.eq("domain_id", domain.getId()));
		c.setProjection(Projections.property("id"));
		return cast(c.uniqueResult());
	}
}
